package com.kyh.util.freemarker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Template;

public class FreemarkerUtil {
	
	
	/**
	 * 
	 * @param toRealPath 所要存放的文件夹绝对路径，格式如E://tomcat/webapps/ROOT
	 * @param toFilename 所要生成的目标文件名称，格式如：xxx.ftl
	 * @param dataMap
	 */
	public static void generateByClass(String fromClasspath, String toRealPath, String toFilename, Map<String, Object> dataMap) {

		File file = new File(toRealPath + "/");
		if (!file.exists()) {
			file.mkdirs();
		}
		String fromFilename = "code.ftl";
		File toFile = new File(toRealPath + "/" + toFilename);
		try {
			generateFileByClassload(fromFilename, fromClasspath, toFile, dataMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @param fromRealpath 模板文件所在的文件夹绝对路径，格式如E://tomcat/webapps/ROOT/t
	 * @param fromFilename 模板文件的文件名称，格式如：xxx.ftl
	 * @param toRealPath 所要存放的文件夹绝对路径，格式如E://tomcat/webapps/ROOT
	 * @param toFilename 所要生成的目标文件名称，格式如：xxx.ftl
	 * @param dataMap
	 */
	public static void generateByRealpath(
			String fromRealpath,
			String fromFilename,
			String toRealPath,
			String toFilename,
			Map<String, Object> dataMap
			) {
		
		// 创建目标文件夹
		File toFolder = new File(toRealPath + "/");
		if (!toFolder.exists()) {
			toFolder.mkdirs();
		}
		
		File toFile = new File(toRealPath + "/" + toFilename);
		try {
			generateFileByRealpathLoad(fromFilename, fromRealpath, toFile, dataMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void generateFileByClassload(final String fromFilename, String fromClasspath, File toFile, Map<String, Object> dataMap)
			throws Exception {
		Template template = FreeMarkerTemplateUtil.getTemplateByClassload(fromFilename, fromClasspath);
		FileOutputStream fos = new FileOutputStream(toFile);
		Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
		template.process(dataMap, out);
	}

	private static void generateFileByRealpathLoad(
			String fromFilename,
			String fromRealpath,
			File toFile,
			Map<String, Object> dataMap
			) throws Exception {
		
		Template template = FreeMarkerTemplateUtil.getTemplateByRealpathLoad(fromFilename, fromRealpath);
		FileOutputStream fos = new FileOutputStream(toFile);
		Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
		template.process(dataMap, out);
	}
}
